package cn.mpq.payment.common.Interceptor;

import cn.mpq.payment.common.Annotation.LoginAnnotation;
import cn.mpq.payment.common.exception.RRException;
import cn.mpq.payment.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
    public static final String USER_KEY = "user";
    /**
     * 在请求处理之前进行调用（Controller方法调用之前），只有返回true才会继续向下执行，返回false取消当前请求
     */
    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
                             Object handler) throws Exception {
        System.out.println("登陆拦截");
        LoginAnnotation annotation = ((HandlerMethod) handler).getMethodAnnotation(LoginAnnotation.class);
        if(annotation == null){
            return true;
        }
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if ( user==null ){
            throw new RRException("请登录");
        }
        //设置userId到request里，后续根据userId，获取用户信息
        arg0.setAttribute(USER_KEY, user);
        return true;
    }

}
